package com.coollang.smartbra.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.coollang.smartbra.R;
import com.coollang.smartbra.activity.LoginActivity;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.constant.Constants;
import com.coollang.smartbra.http.MyHttp;
import com.coollang.smartbra.interfaces.TextChangeListener;
import com.coollang.smartbra.presenter.RegistFragmentPresenter;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.StringUtils;
import com.coollang.smartbra.utils.ToastUtils;
import com.coollang.smartbra.utils.UIUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 注册页面
 */

public class RegistFragment extends LoginBaseFragment implements View.OnClickListener {

    @BindView(R.id.tv_regist)
    TextView mTvRegist;
    private View view;
    private Context mContext;
    @BindView(R.id.et_phone)
    EditText etPhoneRegist;
    @BindView(R.id.et_pass)
    EditText etPassRegist;
    @BindView(R.id.et_code)
    EditText etCodeRegist;
    @BindView(R.id.iv_clear_phone_regist)
    ImageView ivClearPhone;
    @BindView(R.id.iv_see_pass_regist)
    ImageView ivSeePass;
    @BindView(R.id.get_code_regist)
    TextView tvGetCode;

    private Handler mHandler = new Handler();

    String phone;
    String pass;
    private RegistFragmentPresenter mFragmentPresenter;

    @Override
    protected View inflateView(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.item_regist, null, false);
        return view;
    }

    @Override
    protected void initView(View view) {
        ButterKnife.bind(this, view);
        mContext = this.getActivity();
        initListener();
    }

    @Override
    protected void initData() {
        mFragmentPresenter = new RegistFragmentPresenter(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_clear_phone_regist:
                etPhoneRegist.setText("");
                ivClearPhone.setVisibility(View.GONE);
                break;

            case R.id.iv_see_pass_regist:
                UIUtils.seePassword(etPassRegist, ivSeePass);
                break;

            case R.id.get_code_regist:
                if (MyApplication.getApplication().hasNet()) {
                    tvGetCode.setClickable(false);
                    getCode();
                }
                break;
            case R.id.tv_regist:
                if (MyApplication.getApplication().hasNet()) {
                    doRegist();
                }
                break;
        }
    }

    /**
     * 注册监听
     */
    private void initListener() {
        mTvRegist.setOnClickListener(this);
        UIUtils.setLengthFilter(etPhoneRegist, 11);
        UIUtils.setLengthFilter(etCodeRegist, 4);
        UIUtils.setLengthFilter(etPassRegist, 20);
        ivClearPhone.setOnClickListener(this);
        ivSeePass.setOnClickListener(this);
        tvGetCode.setOnClickListener(this);

        // 对手机号输入框做监听
        listenerPhoneEdit();

        // 对手机密码输入框做监听
        listenerPassWEdit();
    }

    private void listenerPhoneEdit() {
        etPhoneRegist.addTextChangedListener(new TextChangeListener() {
            @Override
            public void onTextChange(String str) {
                if (str.length() == 0) {
                    ivClearPhone.setVisibility(View.GONE);
                } else {
                    ivClearPhone.setVisibility(View.VISIBLE);
                }

                // 限制第一个数字只能输入1
                if (str.length() == 1) {
                    int anInt = Integer.parseInt(str.subSequence(0, 1).toString());
                    if (anInt != 1) {
                        etPhoneRegist.setText("");
                    }
                }
            }

        });

    }

    private void listenerPassWEdit() {
        etPassRegist.addTextChangedListener(new TextChangeListener() {
            @Override
            public void onTextChange(String str) {
                if (str.length() == 0) {
                    ivSeePass.setVisibility(View.GONE);
                } else {
                    ivSeePass.setVisibility(View.VISIBLE);
                }

                if (str.contains(" ")) {
                    str = str.trim();
                    etPassRegist.setText(str.trim());
                    etPassRegist.setSelection(str.length());
                }
            }
        });
    }


    /**
     * 注册
     */
    private void doRegist() {
        phone = etPhoneRegist.getText().toString();
        pass = etPassRegist.getText().toString();
        String code = etCodeRegist.getText().toString();

        if (chekRegist(code)) {
            // mPresenter.register(phone, pass, code);
            mFragmentPresenter.register(phone, pass, code);
        }
    }

    // 验证注册
    private boolean chekRegist(String code) {
        boolean checkOk = true;

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showToast(UIUtils.getString(R.string.phone_null));
            checkOk = false;
        } else if (!StringUtils.matchPhone(phone)) {
            ToastUtils.showToast(UIUtils.getString(R.string.phone_wrong_match));
            checkOk = false;
        } else if (TextUtils.isEmpty(code)) {
            // 验证码为空
            ToastUtils.showToast(UIUtils.getString(R.string.code_null));
            checkOk = false;
        } else if (code.length() < 4) {
            // 验证码格式不正确
            ToastUtils.showToast(UIUtils.getString(R.string.code_short));
            checkOk = false;
        } else if (TextUtils.isEmpty(pass)) {
            // 密码为空
            ToastUtils.showToast(UIUtils.getString(R.string.pass_null));
            checkOk = false;
        } else if (pass.length() < 6) {
            ToastUtils.showToast(UIUtils.getString(R.string.pass_short));
            checkOk = false;
        }
        return checkOk;
    }

    /**
     * 获取短信验证码
     */
    private void getCode() {
        String phone = etPhoneRegist.getText().toString();

        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showToast(UIUtils.getString(R.string.error301));
            tvGetCode.setClickable(true);
        } else if (!StringUtils.matchPhone(phone)) {//号码格式校验
            tvGetCode.setClickable(true);
            ToastUtils.showToast(UIUtils.getString(R.string.error_phone));
        } else {
            setTime();
            // 判断用户是否注册
            // mPresenter.checkUserIsRegister(phone);

            mFragmentPresenter.checkUserIsRegister(phone);
        }
    }


    // 获取短信验证码失败
    public void getSMSCodeFaild() {
        time = -1;
    }

    private int time = 60;

    private void setTime() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {

                if (time < 0) {
                    time = 60;
                    tvGetCode.setClickable(true);
                    tvGetCode.setText(R.string.get_code);
                } else {
                    String str = mContext.getResources().getString(R.string.get_code_again);
                    tvGetCode.setText(str + "(" + time + ")");
                    // setTime();
                    time--;
                    mHandler.postDelayed(this, 1000);
                }
            }
        });
    }

    @Override
    protected void setRegisterPhone(String phone) {
        etPhoneRegist.setText(phone);
    }

    @Override
    public void onPause() {
        super.onPause();
        tvGetCode.setClickable(true);
        mHandler.removeCallbacksAndMessages(null);
    }

    // 用户已经注册
    public void userIsRegister() {
        getSMSCodeFaild();
        showIsLoginDialog();
    }

    // 用户未注册
    public void userUnRegister() {
        // mPresenter.getCode(etPhoneRegist.getText().toString());
        mFragmentPresenter.getCode(etPhoneRegist.getText().toString());
        // setTime();
    }

    private void showIsLoginDialog() {
        AlertDialog dialog = new AlertDialog.Builder(getActivity()).create();
        dialog.setMessage("该手机号已注册");
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "去登录", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 切换到注册页面,同时将手机号码也切换过去
                LoginActivity activity = (LoginActivity) mContext;
                activity.goToLoginView();
                // 向注册页面传递手机号码
                activity.getBaseFragment().setLoginrPhone(etPhoneRegist.getText().toString());
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

        Button posiviveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        posiviveButton.setTextColor(Color.parseColor("#F79444"));
        Button negativeButton = dialog.getButton(DialogInterface.BUTTON_NEGATIVE);
        negativeButton.setTextColor(Color.parseColor("#000000"));
    }

    public void onIsRegister(int data) {
        if (data == 1) {
            // 已经被注册
            userIsRegister();
        } else if (data == 0) {
            // 没有注册
            userUnRegister();
        }
    }

    public void goToWelcomeAct() {
        ToastUtils.showToast("注册成功");

        // 直接跳转到欢迎页面
        ActivitySwitcher.goToWelcomeAct(getActivity(), Constants.WELCOME_FROMFIRSTLOGIN);
        getActivity().finish();
    }


    public void onLoginFailed(int errorCode) {
        getSMSCodeFaild();
        MyHttp.getInstance().showErrorToast(getActivity(), errorCode);
    }
}
